#include "showbmp.h"

int *lcd_p = NULL;
int x, y;

void showInit()
{
	// 1. 访问LCD液晶
	int lcd = open("/dev/fb0", O_RDWR);
	if (lcd < 0)
		printf("open lcd error!\n");

	// 2. 根据文件描述符fd申请一片内存，进行映射。
	lcd_p = (int *)mmap(NULL, 800 * 480 * 4, PROT_READ | PROT_WRITE, MAP_SHARED, lcd, 0);
	if (lcd_p == (void *)-1)
	{
		printf("mmap error!\n");
	}
}

//函数功能：显示bmp图片
//参数：file_name 图片名字
//参数：x,y 显示位置坐标
void show_bmp(char *file_name, int set_x, int set_y)
{
	int offset = 0, width = 0, length = 0, x = 0, y = 0;
	short bpp = 0;

	int bmp_fd = open(file_name, O_RDWR);
	if (bmp_fd < 0)
		perror("open bmp error..\n");

	lseek(bmp_fd, 0xA, SEEK_SET);
	read(bmp_fd, &offset, 4);
	printf("offset:%d\n", offset);

	lseek(bmp_fd, 0x12, SEEK_SET);
	read(bmp_fd, &length, 4);
	read(bmp_fd, &width, 4);
	printf("length:%d\n,width:%d\n", length, width);

	lseek(bmp_fd, 0x1C, SEEK_SET);
	read(bmp_fd, &bpp, 2);
	printf("bpp:%d\n", bpp);

	char bmp_data[800 * 480 * bpp / 8];

	lseek(bmp_fd, offset, SEEK_SET);
	read(bmp_fd, &bmp_data, sizeof(bmp_data));

	unsigned char R, G, B;
	char *bmp_p = bmp_data;
	int lcd_data = 0;

	for (y = width - 1; y >= 0; y--)
		for (x = 0; x < length; x++)
		{

			B = *bmp_p++;
			G = *bmp_p++;
			R = *bmp_p++;

			lcd_data = R << 16 | G << 8 | B;

			memcpy(lcd_p + (x + set_x) + (y + set_y) * 800, &lcd_data, 4);
		}

	close(bmp_fd);
}

void show_color()
{
		//1. 访问LCD液晶
	int lcd = open("/dev/fb0",O_RDWR);
	if(lcd < 0)
		printf("open lcd error!\n");
	
	//2. 根据文件描述符fd申请一片内存，进行映射。
	int *p = NULL;
	p = (int *)mmap(NULL,800*480*4,PROT_READ|PROT_WRITE,MAP_SHARED,lcd,0);
	if(p == (void *)-1)
		printf("mmap error!\n");
	
	//3. 准备填充颜色到内存空间上。
	int color = 0x00FF00FF;  //紫色 WRGB
	int write =0x00ffffff;
    int black=0x00000000;
	int i;
	
	for(i=0;i<800*480;i++)
	{
		memcpy(p+i,&black,4);
	}
	
	//4. 撤销内存空间，关闭文件
	munmap(p,800*480*4);
	close(lcd);
}